package com.cowcowit.springcloud.controller;

import com.cowcowit.springcloud.entity.Storage;
import com.cowcowit.springcloud.result.ResultData;
import com.cowcowit.springcloud.service.IStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author whboy
 * @since 2025-09-23
 */
@RestController
@RequestMapping("/springcloud/storage")
public class StorageController {
    
    @Autowired
    private IStorageService storageService;
    
    /**
     * 扣减库存
     */
    @RequestMapping("/decrease")
    public ResultData decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count) {
        storageService.decrease(productId, count);
        return ResultData.success("扣减库存成功!");
    }
    /**
     * 新增库存记录
     * @param storage 库存对象
     * @return 操作结果
     */
    @PostMapping("/add")
    public ResultData<String> addStorage(@RequestBody Storage storage) {
        boolean result = storageService.save(storage);
        if (result) {
            return ResultData.success("库存添加成功");
        } else {
            return ResultData.fail("500", "库存添加失败");
        }
    }
    
    /**
     * 根据ID删除库存记录
     * @param id 库存ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{id}")
    public ResultData<String> deleteStorageById(@PathVariable("id") Long id) {
        boolean result = storageService.removeById(id);
        if (result) {
            return ResultData.success("库存删除成功");
        } else {
            return ResultData.fail("500", "库存删除失败");
        }
    }
    
    /**
     * 更新库存记录
     * @param storage 库存对象
     * @return 操作结果
     */
    @PostMapping("/update")
    public ResultData<String> updateStorage(@RequestBody Storage storage) {
        boolean result = storageService.updateById(storage);
        if (result) {
            return ResultData.success("库存更新成功");
        } else {
            return ResultData.fail("500", "库存更新失败");
        }
    }
    
    /**
     * 根据ID获取库存信息
     * @param id 库存ID
     * @return 库存信息
     */
    @GetMapping("/get/{id}")
    public ResultData<Storage> getStorageById(@PathVariable("id") Long id) {
        Storage storage = storageService.getById(id);
        return ResultData.success(storage);
    }
    
    /**
     * 查询所有库存记录
     * @return 所有库存记录列表
     */
    @GetMapping("/list")
    public ResultData<List<Storage>> getAllStorages() {
        List<Storage> storages = storageService.list();
        return ResultData.success(storages);
    }
}